// pages/agency/index.js
var api = require('../../utils/serve')
var app = getApp();
import tool from "../../utils/tool.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsnum: [{
      num: 0
    }, {
      num: 0
    }, {
      num: 0
    }, {
      num: 0
    }],
    gooodlist: "",
    zonjia: 0,
    payData: [],
    aarr: [],
    userId: '',
    result: [],
    allnum:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.userId = wx.getStorageSync('userId')
    this.getgoodlist()
    var dengji = wx.getStorageSync('loginuser');
    console.log(dengji);
     //计算升下一级需要的钱
     if (dengji.levelName == '会员') {
      // this.data.fuoumoney=9000-dengji.repurchaseSpend
      console.log(this.data.fuoumoney);
      this.setData({
        fuoumoney: 9000 - dengji.repurchaseSpend,
        allnum:1
      })
  
    } else if (dengji.levelName == '网点') {
      this.setData({
        fuoumoney: 50000 - dengji.repurchaseSpend,
        allnum:2
      })
    }else if (dengji.levelName == '推广站') {
      console.log(this.data.fuoumoney);
  
      this.setData({
        fuoumoney: 50000 - dengji.repurchaseSpend,
        allnum:2
      })
    }
     else  if (dengji.levelName == '总代') {
      this.setData({
        fuoumoney: 0,
        allnum:2
      })
    }else{
      this.setData({
        fuoumoney: 0,
        allnum:2
      })
    }
  },
  //计算总价
  onChanges(event) {
    console.log(event);
    this.setData({
      result: event.detail,
    });
    
   this.prcpic()
  },
    // 输入数量
    inputCount(e) {
        console.log(e,111)
        let index = e.currentTarget.dataset.index;
        let goodid =  e.currentTarget.dataset.id
        let num = e.detail.value;
        this.setData({
          num:num
        })
        //修改数量
        api.post('/zkxj/cart/area/updateGoods',{ 
            "goodAreaDetail": 3,
            "goodId": goodid,
            "level": wx.getStorageSync('loginuser').level,
            "num":num,
            "userId": this.data.userId,
        }).then(res => {
            if (res.data.code === 0) {
                this.getgoodlist()
                this.prcpic()
            }else{
              wx.showToast({
                title: '已是最少加购条数！',
                icon: 'error',
                duration: 1000,
                mask: true
              })
             }
          })
       
    },
      // 失去焦点时判断数量是否小于1
   bindblur(e) {
    let index = e.currentTarget.dataset.index;
    let num = e.detail.value;
    let goodid =  e.currentTarget.dataset.id
    this.prcpic()
    // if(num < 2){
    // wx.showToast({
    //  title: '数量不能小于2',
    //  icon: 'none'
    // })
    // num = 2;
    //  this.setData({
    //    num:num
    //  })
    // }
 
    //修改数量
    api.post('/zkxj/cart/area/updateGoods',{ 
        "goodAreaDetail": 3,
        "goodId": goodid,
        "num":num,
        "level": wx.getStorageSync('loginuser').level,
        "userId": this.data.userId,
    }).then(res => {
        if (res.data.code === 0) {
            this.getgoodlist()
            this.prcpic()
        }else{
          wx.showToast({
            title: '已是最少加购条数！',
            icon: 'error',
            duration: 1000,
            mask: true
          })
         }
      })
   },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  //空函数
  catchtap() {

  },
   //删除商品
   handleletes(e){
    console.log(e);
 const goodid = e.currentTarget.dataset['index'] || 0
     
   wx.request({
    url: app.globalData.url+'/zkxj/cart/area/deleteGoods',
    data: {
      "goodAreaDetail": 3,
      "goodId": goodid,
      "level": wx.getStorageSync('loginuser').level,
      "userId": this.data.userId,
    },
    method: 'POST',
    header: {
      'content-type': 'application/json',
      'token': wx.getStorageSync('token')
    },
    success: (res) => {
      if (res.data.code == 0) {
        //请求商品列表
        wx.request({
          url: app.globalData.url+'/zkxj/cart/area/queryGoodsListByUserId',
          data: {
            "userId": this.data.userId,
            "goodAreaDetail":3,
            "level": wx.getStorageSync('loginuser').level
          },
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          success: (res) => {
            if(res.data.code==0){
              wx.showToast({
                title: '删除成功！',
                icon: 'success',
                duration: 1000,
                mask: true
              })
              this.setData({
                gooodlist: res.data.data,
              });
                //计算价格
            this.prcpic()
            }
          },
        })
      }
    },
  })
  },
  // 请求商品
getgoodlist(){
//请求商品列表
wx.request({
  url: app.globalData.url+'/zkxj/cart/area/queryGoodsListByUserId',
  data: {
    "userId": this.data.userId,
    "goodAreaDetail": 3,
    "level": wx.getStorageSync('loginuser').level
  },
  method: 'POST',
  header: {
    'content-type': 'application/json',
    'token': wx.getStorageSync('token')
  },
  success: (res) => {
    this.setData({
      gooodlist: res.data.data,
    });
    console.log(this.data.gooodlist);
  },
})
},
  // 计算价格
  prcpic(){
    let res = this.data.result
    console.log(res);
    let prcnum = 0
    var allarr = []
    for (let i = 0; i < res.length; i++) {
      console.log(parseInt(res[i]));
      console.log(this.data.gooodlist[parseInt(res[i])]);
      allarr.push(this.data.gooodlist[parseInt(res[i])])
    }
    console.log(allarr);
      for (let k = 0; k < allarr.length; k++) {
        prcnum += allarr[k].price * allarr[k].num
      }
       console.log(prcnum);
      this.setData({
        zonjia: prcnum
      })
  },
 
   handledelae: tool.throttle(function (e) {
     console.log(this.data.allnum);
    const goodid = e[0].currentTarget.dataset['index'] || 0
    const price = e[0].currentTarget.dataset['price'];
    const oldprice = e[0].currentTarget.dataset['oldprice'];
    const num = e[0].currentTarget.dataset['num'] - 1;
    let minnum=this.data.allnum
    console.log(num,'num')
   
      //修改购物车数量
   wx.request({
     url: app.globalData.url+'/zkxj/cart/area/updateGoods',
     data: {
       "goodAreaDetail": 3,
       "goodId": goodid,
       "num":num,
       "level": wx.getStorageSync('loginuser').level,
       // "oldPrice": oldprice,
       "userId": this.data.userId,
       // "price": price,
     },
     method: 'POST',
     header: {
       'content-type': 'application/json',
       'token': wx.getStorageSync('token')
     },
     success: (res) => {
       if (res.data.code == 0) {
         //请求商品列表
         wx.request({
           url: app.globalData.url+'/zkxj/cart/area/queryGoodsListByUserId',
           data: {
             "userId": this.data.userId,
             "goodAreaDetail": 3,
             "level": wx.getStorageSync('loginuser').level
           },
           method: 'POST',
           header: {
             'content-type': 'application/json',
             'token': wx.getStorageSync('token')
           },
           success: (res) => {
             if(res.data.code==0){
               
               this.setData({
                 gooodlist: res.data.data,
               });
                 //计算价格
             this.prcpic()
             }
           },
         })
       }else{
        wx.showToast({
          title: '已是最少加购条数！',
          icon: 'error',
          duration: 1000,
          mask: true
        })
       }
     },
   })
    
  }),
  handledeadd: tool.throttle(function (e) {
    const goodid = e[0].currentTarget.dataset['index'] || 0
    const price = e[0].currentTarget.dataset['price'];
    const num = e[0].currentTarget.dataset['num'] + 1;
     //修改购物车数量
     wx.request({
      url: app.globalData.url+'/zkxj/cart/area/updateGoods',
      data: {
        "goodAreaDetail": 3,
        "goodId": goodid,
        "num":num,
        "level": wx.getStorageSync('loginuser').level,
        // "oldPrice": oldprice,
        "userId": this.data.userId,
        // "price": price,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code == 0) {
          //请求商品列表
          wx.request({
            url: app.globalData.url+'/zkxj/cart/area/queryGoodsListByUserId',
            data: {
              "userId": this.data.userId,
              "goodAreaDetail": 3,
              "level": wx.getStorageSync('loginuser').level
            },
            method: 'POST',
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token')
            },
            success: (res) => {
              if(res.data.code==0){
                
                this.setData({
                  gooodlist: res.data.data,
                });
                  //计算价格
              this.prcpic()
              }
            },
          })
        
        }
      },
    })
    
  }),
    handletobuy() {
    // console.log(this.data.gooodlist);
    // console.log(this.data.result);
    let res = this.data.result
    console.log(res);
    let prcnum = 0
    var allarr = []
    for (let i = 0; i < res.length; i++) {
      console.log(parseInt(res[i]));
      // console.log(this.data.gooodlist[parseInt(res[i])]);
      allarr.push(this.data.gooodlist[parseInt(res[i])])
    }
    console.log(allarr);
    //整理数据格式
   
    let result = [];//结果保存
    for (let i = 0; i < allarr.length; i++) {
      delete allarr[i].createtime;
      delete allarr[i].modifiedtime;
      delete allarr[i].unit;
      delete allarr[i].userId;
      delete allarr[i].id;
      allarr[i].oldpric=allarr[i].price
      allarr[i].goodId=allarr[i].goodId
      console.log(allarr[i].goodId);
      allarr[i].price=allarr[i].price
       //获取到list的第i个对象，修改后返回一个新对象，不修改原对象
       var resss = JSON.parse(JSON.stringify(allarr[i]).replace(/goodId/g, 'id').replace(/quantity/g, "num"));
       console.log(resss);
       result.push(resss)
      
      }
    console.log(result);
    var detailsData = JSON.stringify(result);
    detailsData = encodeURIComponent(detailsData);
    wx.navigateTo({
      url: `/pages/seaccounts/index?arr=${detailsData}&sum=${JSON.stringify(this.data.zonjia)}&type=2&upgradeLevel=0`
    })
    console.log(this.data.payData);
    // if (this.data.aarr.length) {
    //   console.log(this.data.aarr);
    //   var detailsData = JSON.stringify(this.data.aarr);
    //   detailsData = encodeURIComponent(detailsData);
    //   wx.navigateTo({
    //     url: `/pages/zdseepg/index?arr=${detailsData}&sum=${JSON.stringify(this.data.zonjia)}&type=4&upgradeLevel=0`
    //   })
    // } else {
    //   wx.showToast({
    //     title: '你还未选购商品',
    //     icon: 'error',
    //     duration: 1000,
    //     mask: true
    //   })
    // }
  },
  handletobuys(){
    wx.showToast({
          title: '你还未选购商品',
          icon: 'error',
          duration: 1000,
          mask: true
        })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})